package com.gin.no_gay_alliance.manager.provider;

import com.fasterxml.jackson.core.type.TypeReference;
import com.gin.jackson.utils.JacksonUtils;
import com.gin.nga.resource.ResourceProvider;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.viewmodel.AppRelease;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Objects;

import okhttp3.HttpUrl;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 版本提供者
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/20 00:04
 **/
public class VersionProvider extends ResourceProvider<ArrayList<AppRelease>> {
    /**
     * 请求地址
     */
    public static final String URL = "https://gitee.com/api/v5/repos/AgMonk/no-gay-alliance-for-android/releases";

    public VersionProvider(int page, int size) {
        super(buildUrl(page, size),
                MyApplication.app.okHttpClient,
                ResourceManager.getRecourceCacheFile(buildFilename(page, size)),
                ResourceManager.EXPIRES);
    }

    @Override
    protected ArrayList<AppRelease> readCache(File cacheFile) throws IOException {
        return JacksonUtils.MAPPER.readValue(cacheFile, new TypeReference<ArrayList<AppRelease>>() {
        });
    }

    /**
     * 将响应转换为指定类型数据的方法
     *
     * @param response 响应
     * @return T
     */
    @Override
    protected ArrayList<AppRelease> convert(Response response) throws IOException {
        if (response.code() == 200) {
            try (ResponseBody responseBody = response.body()) {
                if (responseBody != null) {
                    return JacksonUtils.MAPPER.readValue(responseBody.byteStream(), new TypeReference<ArrayList<AppRelease>>() {
                    });
                }
            }
        }
        throw new IOException(String.format(Locale.CHINA, "code: %d 响应数据为空", response.code()));
    }

    private static String buildUrl(int page, int size) {
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(URL)).newBuilder();
        urlBuilder.addQueryParameter("page", String.valueOf(page));
        urlBuilder.addQueryParameter("per_page", String.valueOf(size));
        // 倒序
        urlBuilder.addQueryParameter("direction", "desc");
        return urlBuilder.build().toString();
    }

    private static String buildFilename(int page, int size) {
        return String.format(Locale.CHINA, "releases_%d_%d.json", page, size);
    }
}
